const webpack = require('webpack');
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const WebpackDevServe = require('webpack-dev-server')

const config = {
	entry: [
		'react-hot-loader/patch',
		'./src/index.tsx'
	],
	output: {
		path: path.resolve(__dirname, 'dist'),
		filename: '[name].[contenthash].js'
	},
	module: {
		rules: [
			{
				test: /\.(js|jsx)$/,
				use: 'babel-loader',
				exclude: /node_modules/
			},
			{
				test: /\.css$/,
				use: [
					MiniCssExtractPlugin.loader,
					{
						loader: 'css-loader',
						options: {
							importLoaders: 1
						}
					},
					'postcss-loader'
				]
			},
			{
				test: /\.ts(x)?$/,
				loader: 'ts-loader',
				exclude: /node_modules/
			},
			{
				test: /\.scss$/,
				use: [
					MiniCssExtractPlugin.loader,
					'css-loader',
					'sass-loader'
				]
			},
			{
				test: /\.svg$/,
				use: 'file-loader'
			},
			{
				test: /\.png$/,
				use: [
					{
						loader: 'url-loader',
						options: {
							mimetype: 'image/png'
						}
					}
				]
			}
		]
	},
	resolve: {
		extensions: [
			'.js',
			'.jsx',
			'.tsx',
			'.ts'
		],
		alias: {
			'react-dom': '@hot-loader/react-dom'
		}
	},
	devServer: {
		// contentBase: './dist'
		port: 8080,
		host: '0.0.0.0',
		compress: true,
		hot: true,
		open: true
	},
	devtool: 'source-map',
	plugins: [
		new CopyPlugin({
			patterns: [{ from: 'src/banner.txt' }],
		}),
		// new HtmlWebpackPlugin({
		//   templateContent: ({ htmlWebpackPlugin }) => '<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>' + htmlWebpackPlugin.options.title + '</title></head><body><div id=\"app\"></div></body></html>',
		//   filename: 'index.html',
		// }),
		new HtmlWebpackPlugin({
			filename: 'index.html',
			template: './public/index.html'
		}),
		new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
		new LodashModuleReplacementPlugin,
		new BundleAnalyzerPlugin({
			analyzerMode: 'static',
			openAnalyzer: false,
		}),
		new MiniCssExtractPlugin(),
		new CleanWebpackPlugin()
	],
	optimization: {
		runtimeChunk: 'single',
		splitChunks: {
			cacheGroups: {
				vendor: {
					test: /[\\/]node_modules[\\/]/,
					name: 'vendors',
					chunks: 'all'
				}
			}
		}
	}
};

// module.exports = (env, argv) => {
// 	if (argv.hot) {
// 		// Cannot use 'contenthash' when hot reloading is enabled.
// 		config.output.filename = '[name].[hash].js';
// 	}

// 	return config;
// };

const compiler = webpack(config)
const serve = new WebpackDevServe(config, compiler)

// module.exports = serve
serve.listen(8080, ()=>{
	console.log('启动成功')
})